import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:share_plus/share_plus.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:oramemo/common/langs/text_key.dart';

class ShareDialog extends StatelessWidget {
  final String title;
  final String audioUrl;
  final List<String> transcripts;

  const ShareDialog({
    Key? key,
    required this.title,
    required this.audioUrl,
    required this.transcripts,
  }) : super(key: key);

  Future<void> _shareText() async {
    final text = transcripts.join('\n\n');
    await Share.share(text, subject: title);
  }

  Future<void> _shareAudio() async {
    try {
      // 下载音频文件
      final file = await DefaultCacheManager().getSingleFile(audioUrl);

      // 分享文件
      await Share.shareXFiles(
        [XFile(file.path)],
        text: title,
      );
    } catch (e) {
      print('Error sharing audio: $e');
    }
  }

  Future<void> _shareAll() async {
    try {
      // 下载音频文件
      final file = await DefaultCacheManager().getSingleFile(audioUrl);

      // 准备文本内容
      final text = transcripts.join('\n\n');

      // 分享文件和文本
      await Share.shareXFiles(
        [XFile(file.path)],
        text: '$title\n\n$text',
      );
    } catch (e) {
      print('Error sharing all: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              TextKey.share.tr,
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 24),
            _buildShareOption(
              icon: Icons.text_fields,
              title: TextKey.transcriptionDetailsShareText.tr,
              onTap: _shareText,
            ),
            _buildShareOption(
              icon: Icons.audio_file,
              title: TextKey.shareAudio.tr,
              onTap: _shareAudio,
            ),
            _buildShareOption(
              icon: Icons.all_inclusive,
              title: TextKey.shareAll.tr,
              onTap: _shareAll,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildShareOption({
    required IconData icon,
    required String title,
    required VoidCallback onTap,
  }) {
    return ListTile(
      leading: Icon(icon),
      title: Text(title),
      onTap: () async {
        onTap();
      },
    );
  }
}
